package top.lingchen.blogapi.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.lingchen.blogapi.utils.QiniuUtils;
import top.lingchen.blogapi.vo.Result;

import java.util.UUID;

import static top.lingchen.blogapi.vo.ErrorCode.FILE_UPLOAD_FAIL;

/**
 * @Author 凌宸
 * @create 2021-12-17 下午 6:44
 * @Description
 * @Version 1.0
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private QiniuUtils qiniuUtils;

    @PostMapping
    public Result upload(@RequestParam("image")MultipartFile file){
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 保证文件名唯一
        String filename = UUID.randomUUID() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        // 上传到七牛云
        boolean upload = qiniuUtils.upload(file, filename);
        if(upload){
            return Result.success(QiniuUtils.url + filename);
        }
        return Result.fail(FILE_UPLOAD_FAIL.getCode(), FILE_UPLOAD_FAIL.getMsg());
    }
}
